import { generateGlobalRoutesAndApis, generateCurrentUserRoutesAndApis } from '$lib/utils/generateRoutesAndApis';
import { SETUP_ROUTES_APIS, AUTH_TOKEN, LOGIN_COOKIE_CONFIG, ROUTE_LOGIN, ROUTE_PERMISSION_DENIED } from '$lib/config/variable';
import jwt from '$lib/utils/jwt';
import permissionsModule from '$lib/modules/permissions';
import usersModule from "$lib/modules/users";
import { redirect } from '@sveltejs/kit';

export async function handle({ event, resolve }) {
  try {
    const allPermissions = await permissionsModule.getAll();
    const pathname = event.url.pathname;
    if (!allPermissions?.length) return resolve(event);
    const authHandles = allPermissions.map(p => p.handle);
    const {routes, apis, handles} = generateGlobalRoutesAndApis(authHandles);
    const token = event.cookies.get(AUTH_TOKEN);
    const isRouteNeedLogin = routes.some(r => pathname.startsWith(r));
    const isApiNeedLogin = apis.some(a => pathname.startsWith(a));
    if (!isRouteNeedLogin && !isApiNeedLogin) return resolve(event);

    if ((isRouteNeedLogin || isApiNeedLogin) && !token) {
      if (isRouteNeedLogin) throw redirect(302, ROUTE_LOGIN);
      if (isApiNeedLogin) return new Response(JSON.stringify({ message: '未登录', status: false }), { status: 401, headers: { 'Content-Type': 'application/json' } });
    }

    const verifiedToken = await jwt.verify(token);
    if (!verifiedToken) {
      if (isRouteNeedLogin) throw redirect(302, ROUTE_LOGIN);
      if (isApiNeedLogin) return new Response(JSON.stringify({ message: '登录已过期', status: false }), { status: 401, headers: { 'Content-Type': 'application/json' } });
    }

    const { payload: { id, username } } = verifiedToken;
    const user = await usersModule.getByUsername(username);
    const currentUserPermissions = (await permissionsModule.getByRoleId(user.role_id)).permissions;
    const currentUserHandles = currentUserPermissions.length > 0 ? currentUserPermissions.map(p => p.handle) : [];
    const currentUserRoutesAndApis = generateCurrentUserRoutesAndApis(currentUserHandles);
    const newToken = await jwt.generate({ id: user.id, username: user.username, permissions: currentUserRoutesAndApis });
    event.cookies.set(AUTH_TOKEN, newToken, LOGIN_COOKIE_CONFIG);
    if (isRouteNeedLogin && !currentUserRoutesAndApis.routes.some(r => pathname.startsWith(r))) { throw redirect(302, ROUTE_PERMISSION_DENIED); }
    if (isApiNeedLogin && !currentUserRoutesAndApis.apis.some(a => pathname.startsWith(a))) { return new Response(JSON.stringify({ message: '权限不足', status: false }), { status: 403, headers: { 'Content-Type': 'application/json' } }); }

    return resolve(event);
  } catch (error) {
    if (error && error.status === 302 && error.location) throw error;
    return resolve(event);
  }
}